<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import HeaderNav from '../../components/layout/HeaderNav.vue'
import AdminHeaderNav from '../../components/layout/AdminHeaderNav.vue'
import { getProductDetailsService, type Product } from '../../api/product' 
import { Star } from '@element-plus/icons-vue' 
import { useUserStore } from '../../stores/user'
import { addCart } from '../../api/cart'
import { ElMessage } from 'element-plus'
import Reviews from '../../components/product/Reviews.vue'

const route = useRoute()
const userStore = useUserStore()
const product = ref<Product | null>(null)
const loading = ref(false)
const currentImageIndex = ref(0)
const quantity = ref(1)
const currentTab = ref('reviews') // 当前选中的标签页
const reviewsComponent = ref<any>(null) // Reviews组件引用
const totalReviewCount = ref(0) // 总评论数

// 计算显示的评论数，优先使用 Reviews 组件传递的数据，否则使用商品数据
const displayReviewCount = computed(() => {
  return totalReviewCount.value || product.value?.commentCount || 0
})

// 根据用户类型决定显示哪个导航栏（role===3 为管理员）
const isAdmin = computed(() => userStore.isAdmin)

// 商品图片列表
const productImages = computed(() => {
  if (!product.value) return []
  return [
    product.value.image,
    product.value.image, // 这里可以根据实际数据结构调整
    product.value.image,
    product.value.image
  ]
})

// 当前显示的图片
const currentImage = computed(() => {
  return productImages.value[currentImageIndex.value] || ''
})

// 获取商品详情
const fetchProductDetail = async () => {
  const productId = Number(route.params.id)
  if (!productId) return
  
  try {
    loading.value = true
    const response = await getProductDetailsService(productId)
    if (response.data) {
      product.value = response.data
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 显示图片预览
const showImagePreview = () => {
  // 这里可以添加图片预览功能
  console.log('显示图片预览')
}

// 增加商品数量
const increaseQuantity = () => {
  if (product.value && quantity.value < product.value.stock) {
    quantity.value++
  } else {
    ElMessage.info('已达到最大库存数量')
  }
}

// 减少商品数量
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

const addToCart=async()=>{
  if(!product.value){
    ElMessage.warning('商品信息未加载完成，请稍后重试')
    return
  }
  
  if(!userStore.isLoggedIn || !userStore.userId) {
    ElMessage.warning('请先登录再加入购物车')
    return
  }
  
  try{
    // 构建请求参数，包含用户ID和商品信息
    const requestData = {
      userId: Number(userStore.userId), // 添加用户ID
      itemId: product.value.id,
      num: quantity.value,
      spec: product.value.spec || '',
      name: product.value.name,
      image: product.value.image,
      price: product.value.price
    }
    console.log('加入购物车请求数据:', requestData)
    
    const res = await addCart(requestData) as any
    console.log('加入购物车API返回:', res)
    
    // 由于request拦截器返回response.data，所以res直接就是后端的Result对象
    // 格式：{code: 0, message: "操作成功", data: null}
    if (res?.code === 0) {
      // 成功加入购物车
      ElMessage.success('加入购物车成功，请到购物车查看')
      // 重置数量为1
      quantity.value = 1
    } else {
      // 后端返回错误信息
      const errorMsg = res?.message || '加入购物车失败'
      ElMessage.error(errorMsg)
    }
  } catch(error) {
    console.error('加入购物车异常:', error)
    ElMessage.error('加入购物车异常，请稍后重试')
  }
}
// 解析规格参数
const parsedSpecs = computed(() => {
  if (!product.value?.spec) return null
  
  try {
    // 尝试解析JSON格式
    if (product.value.spec.startsWith('{') && product.value.spec.endsWith('}')) {
      return JSON.parse(product.value.spec)
    }
    
    // 解析分号分隔的格式 "颜色:绿色;尺码:26寸"
    const specs: { [key: string]: string } = {}
    const specArray = product.value.spec.split(';')
    
    specArray.forEach(item => {
      if (item.trim()) {
        const [key, value] = item.split(':')
        if (key && value) {
          specs[key.trim()] = value.trim()
        }
      }
    })
    
    return Object.keys(specs).length > 0 ? specs : null
  } catch (error) {
    console.error('解析规格信息失败:', error)
    return null
  }
})

// 更新评论总数
const updateReviewCount = (count: number) => {
  console.log('收到评论数更新:', count)
  totalReviewCount.value = count
}

// 刷新商品详情（用于评价变更后重新加载）
const refreshProductDetail = async () => {
  // 保存当前页面滚动位置
  const scrollPosition = {
    x: window.scrollX,
    y: window.scrollY
  }
  
  // 重新加载商品详情（包含评价统计）
  await fetchProductDetail()
  
  // 重新加载评价组件的所有数据（相当于浏览器刷新的效果）
  if (reviewsComponent.value && currentTab.value === 'reviews') {
    // 调用Reviews组件的完整重新加载方法
    await reviewsComponent.value.reloadAllData()
  }
  
  // 恢复页面滚动位置，保持用户浏览位置不变
  window.scrollTo(scrollPosition.x, scrollPosition.y)
}

// 组件挂载时获取商品详情
onMounted(() => {
  fetchProductDetail()
})
</script>

<template>
  <div class="product-detail-container">
    <!-- 顶部导航栏 -->
    <!-- 根据用户类型显示不同的导航栏 -->
    <AdminHeaderNav v-if="isAdmin" />
    <HeaderNav v-else />
    
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 商品图片展示区 -->
      <div class="product-images-section">
        <div class="main-image-container">
          <img 
            :src="currentImage" 
            :alt="product?.name" 
            class="main-image"
            @click="showImagePreview"
          />
        </div>   
      </div>
      
      <!-- 商品信息区 -->
      <div class="product-info-section">
        <!-- 店铺信息 -->
        <div class="store-info">
          <div class="store-left">
            <div class="store-logo">官方</div>
            <div class="store-name">旗舰店</div>
            <div class="tmall-badge">{{ product?.brand }}</div>
          </div>
          <div class="store-actions">
            <div class="action-btn">客服</div>
            <div class="action-btn">进店</div>
          </div>
        </div>
        
        <!-- 商品标题 -->
        <h1 class="product-title">{{ product?.name }}</h1>
        
        <!-- 价格信息 -->
        <div class="price-section">
          <div class="main-price">¥{{ product?.price }}</div>
        </div>
        
        <!-- 销量信息 -->
        <div class="sales-info">
          <span class="sales-label">已售</span>
          <span class="sales-value">{{ product?.sold }}+件</span>
            <span class="stock-label">库存</span>
            <span class="stock-value">{{ product?.stock }}件</span>       
        </div>
      
       
        <!-- 数量选择 -->
        <div class="quantity-selection">
          <h3 class="spec-title">数量</h3>
          <div class="quantity-control">
            <button class="qty-btn minus" @click="decreaseQuantity" :disabled="quantity <= 1"></button>
            <input 
              type="text" 
              class="qty-input" 
              v-model.number="quantity"
              min="1" 
              :max="product?.stock || 99"
              @input="quantity = Math.max(1, Math.min(quantity, product?.stock || 99))"
            />
            <button class="qty-btn plus" @click="increaseQuantity"></button>
          </div>
        </div>
        
        <!-- 颜色/款式选择 -->
        <div class="style-selection">
          <h3 class="spec-title">规格参数</h3>
        
          <!-- 原有的款式选择 -->
          <div class="style-option active" v-if="product?.spec">
            <img :src="product?.image" alt="红色" />
            <div 
              v-for="(options, category) in parsedSpecs" 
              :key="category" 
              class="spec-category"
            >
            <!-- <span>{{ category }}</span> -->
            <span>{{ options }}</span>
            </div>
          </div>
            <!-- 如果没有规格信息，显示"无" -->
          <!-- <div v-else class="style-option active">
            <span class="no-specs-text">暂无规格信息</span>
          </div> -->
          
        </div>
      
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button class="add-to-cart-btn" @click="addToCart">加入购物车</button>
          <!-- <button class="buy-now-btn">领券购买</button> -->
          <div class="favorite-btn">
            <el-icon><Star /></el-icon>
            <span>收藏</span>
          </div>
        </div>
        <!-- 状态栏 ,0-待审核，1-已上架，2-已下架，3-审核未通过-->
        <div class="status-item">
        <span class="status-value">{{ product?.status === 0 ? '待审核' : product?.status === 1 ? '已上架' : product?.status === 2 ? '已下架' : '审核未通过' }}</span>
        </div>
      </div>
      
    </div>
    
   
    
    <!-- 底部导航 -->
    <div class="bottom-navigation">
      <div 
        class="nav-item" 
        :class="{ active: currentTab === 'reviews' }"
        @click="currentTab = 'reviews'"
      >
        用户评价({{ displayReviewCount }})
      </div>
      <div 
        class="nav-item" 
        :class="{ active: currentTab === 'params' }"
        @click="currentTab = 'params'"
      >
        参数信息
      </div>
      <div 
        class="nav-item" 
        :class="{ active: currentTab === 'details' }"
        @click="currentTab = 'details'"
      >
        图文详情
      </div>
      <div 
        class="nav-item" 
        :class="{ active: currentTab === 'recommend' }"
        @click="currentTab = 'recommend'"
      >
        本店推荐
      </div>
      <div 
        class="nav-item" 
        :class="{ active: currentTab === 'related' }"
        @click="currentTab = 'related'"
      >
        看了又看
      </div>
    </div>

    <!-- 标签页内容 -->
    <div class="tab-content" v-if="currentTab === 'reviews'">
      <Reviews 
        v-if="product"
        ref="reviewsComponent"
        :product-id="product.id"
        :avg-score="product.score ?? 0"
        :comment-count="product.commentCount"
        @review-submitted="refreshProductDetail"
        @review-deleted="refreshProductDetail"
        @count-updated="updateReviewCount"
      />
    </div>
    <div class="tab-content" v-else>
      <!-- 其他标签页的占位内容 -->
      <div class="placeholder-content">
        敬请期待
      </div>
    </div>
  </div>
</template>



<style scoped lang="scss">
.product-detail-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 0 2.5rem;
}

.main-content {
  max-width: 75rem;
  margin: 0 auto;
  padding: 1rem 0;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
}

/* 商品图片展示区 */
.product-images-section {
  background: #fff;
  border-radius: 0.5rem;
  padding: 1rem;
  
  .main-image-container {
    position: relative;
    margin-bottom: 1rem;
    
    .main-image {
      width: 100%;
      height: 25rem;
      object-fit: cover;
      border-radius: 0.5rem;
      cursor: pointer;
      transition: transform 0.2s;
      
      &:hover {
        transform: scale(1.02);
      }
    }
    
    .image-overlay {
      position: absolute;
      bottom: 1rem;
      left: 1rem;
      display: flex;
      flex-direction: column;
      gap: 0.25rem;
      
      .overlay-text {
        background: rgba(255, 255, 255, 0.9);
        color: #666;
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.75rem;
      }
    }
  }
  
  .thumbnail-list {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    
    .thumbnail-item {
      width: 4rem;
      height: 4rem;
      border: 2px solid transparent;
      border-radius: 0.25rem;
      cursor: pointer;
      overflow: hidden;
      transition: all 0.2s;
      
      &.active {
        border-color: #ee5530;
      }
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      &.parameter-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f5f5f5;
        color: #666;
        font-size: 0.75rem;
      }
    }
  }
}

/* 商品信息区 */
.product-info-section {
  background: #fff;
  border-radius: 0.5rem;
  padding: 1.5rem;
  
  .store-info {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1rem;
    
    .store-left {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      
      .store-logo {
        width: 2rem;
        height: 2rem;
        background: #ee5530;
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 0.875rem;
      }
      
      .store-name {
        font-weight: 600;
        color: #333;
      }
      
      .tmall-badge {
        background: #ff6b6b;
        color: white;
        padding: 0.125rem 0.375rem;
        border-radius: 0.25rem;
        font-size: 0.625rem;
      }
    }
    
    .store-stats {
      display: flex;
      flex-direction: column;
      gap: 0.25rem;
      
      .rating {
        font-size: 1.25rem;
        font-weight: bold;
        color: #ff6b6b;
      }
      
      .stats-item {
        font-size: 0.75rem;
        color: #666;
      }
    }
    
    .store-actions {
      display: flex;
      gap: 0.5rem;
      
      .action-btn {
        padding: 0.25rem 0.75rem;
        border: 1px solid #ddd;
        border-radius: 0.25rem;
        font-size: 0.75rem;
        cursor: pointer;
        transition: all 0.2s;
        
        &:hover {
          border-color: #ee5530;
          color: #ee5530;
        }
      }
    }
  }
  
  .vip-banner {
    background: linear-gradient(135deg, #ff6b6b, #ee5530);
    color: white;
    padding: 0.75rem 1rem;
    border-radius: 0.5rem;
    margin-bottom: 1rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .vip-btn {
      background: rgba(255, 255, 255, 0.2);
      border: none;
      color: white;
      padding: 0.25rem 0.75rem;
      border-radius: 0.25rem;
      cursor: pointer;
      font-size: 0.75rem;
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
      }
    }
  }
  
  .product-title {
    font-size: 1.125rem;
    color: #333;
    margin-bottom: 1rem;
    line-height: 1.4;
  }
  
  .invoice-option {
    color: #666;
    font-size: 0.875rem;
    margin-bottom: 1rem;
  }
  
  .price-section {
    margin-bottom: 1rem;
    
    .main-price {
      font-size: 1.5rem;
      font-weight: bold;
      color: #ee5530;
      margin-bottom: 0.25rem;
    }
    
    .original-price {
      font-size: 0.875rem;
      color: #999;
      text-decoration: line-through;
    }
  }
  
  .sales-info {
    color: #666;
    font-size: 0.875rem;
    margin-bottom: 1rem;
    .sales-label{
      margin-right: 0.5rem;
    }
    .sales-value{
      margin-right: 2rem;
    }
    .stock-label{
      margin-right: 0.5rem;
    }
   
  }
  
  .promotion-info {
    margin-bottom: 1rem;
    
    .promo-item {
      background: #fff5f5;
      color: #ee5530;
      padding: 0.25rem 0.5rem;
      border-radius: 0.25rem;
      font-size: 0.75rem;
      margin-bottom: 0.25rem;
      display: inline-block;
      margin-right: 0.5rem;
    }
  }
  
  .delivery-info {
    margin-bottom: 1rem;
    
    .delivery-time {
      color: #333;
      font-weight: 600;
      margin-bottom: 0.25rem;
    }
    
    .delivery-details {
      color: #666;
      font-size: 0.875rem;
    }
  }
  
  .guarantee-services {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-bottom: 1rem;
    
    .guarantee-item {
      background: #f8f9fa;
      color: #666;
      padding: 0.25rem 0.5rem;
      border-radius: 0.25rem;
      font-size: 0.75rem;
      border: 1px solid #e9ecef;
    }
  }
  
  .payment-method {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    color: #666;
    font-size: 0.875rem;
    margin-bottom: 1rem;
    
    .info-icon {
      color: #999;
      font-size: 0.875rem;
    }
  }
  
  .quantity-selection {
    margin-bottom: 1.5rem;
    .spec-title {
      margin-bottom: 0.5rem;
    }
    .quantity-control {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      .qty-btn {
        width: 1.5rem;
        height: 1.5rem;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        transition: all 0.2s ease;
        font-size: 0.875rem;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
      }
      .qty-btn.minus {
        background: white;
        border: 1px solid #1890ff;
        color: #1890ff;
      }
      .qty-btn.minus:hover:not(:disabled) {
        background: #f0f8ff;
        transform: scale(1.05);
      }
      .qty-btn.minus:disabled {
        border-color: #d9d9d9;
        color: #d9d9d9;
        cursor: not-allowed;
      }
      .qty-btn.minus::before {
        content: '';
        width: 0.75rem;
        height: 1px;
        background: currentColor;
        position: absolute;
      }
      .qty-btn.plus {
        background: #1890ff;
        color: white;
      }
      .qty-btn.plus:hover:not(:disabled) {
        background: #40a9ff;
        transform: scale(1.05);
      }
      .qty-btn.plus:disabled {
        background: #d9d9d9;
        cursor: not-allowed;
      }
      .qty-btn.plus::before {
        content: '';
        width: 0.75rem;
        height: 1px;
        background: currentColor;
        position: absolute;
      }
      .qty-btn.plus::after {
        content: '';
        width: 1px;
        height: 0.75rem;
        background: currentColor;
        position: absolute;
      }
      .qty-input {
        width: 2.5rem;
        height: 1.5rem;
        text-align: center;
        border: 1px solid #e0e0e0;
        border-radius: 0.25rem;
        outline: none;
        font-size: 0.875rem;
        color: #333;
        background: white;
      }
      .qty-input:focus {
        border-color: #1890ff;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
      }
    }
  }
  
  .style-selection {
    margin-bottom: 1.5rem;
    .spec-title{
      // font-size: 1.25rem;
      // font-weight: 600;
      // color: #333;
      margin-bottom: 0.5rem;
    }
    .style-option {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.5rem;
      border: 2px solid transparent;
      border-radius: 0.25rem;
      cursor: pointer;
      transition: all 0.2s;
      margin-bottom: 0.5rem;
      
      &.active {
        border-color: #ee5530;
        background: #fff5f5;
      }
      
      img {
        width: 2rem;
        height: 2rem;
        object-fit: cover;
        border-radius: 0.25rem;
      }
      
      span {
        font-size: 0.875rem;
        color: #333;
      }
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 1rem;
    align-items: center;
    
    .add-to-cart-btn {
      background: #ffd700;
      color: #333;
      border: none;
      padding: 0.75rem 1.5rem;
      border-radius: 0.5rem;
      font-size: 1rem;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background: #ffed4e;
        transform: translateY(-0.125rem);
      }
    }
    
    .buy-now-btn {
      background: #ee5530;
      color: white;
      border: none;
      padding: 0.75rem 1.5rem;
      border-radius: 0.5rem;
      font-size: 1rem;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background: #d94825;
        transform: translateY(-0.125rem);
      }
    }
    
    .favorite-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 0.25rem;
      cursor: pointer;
      color: #666;
      transition: color 0.2s;
      
      &:hover {
        color: #ee5530;
      }
      
      .el-icon {
        font-size: 1.25rem;
      }
      
      span {
        font-size: 0.75rem;
      }
    }
  }
}

/* 底部导航 */
.bottom-navigation {
  max-width: 75rem;
  margin: 0 auto;
  background: white;
  border-radius: 0.5rem;
  padding: 1rem;
  display: flex;
  justify-content: center;
  gap: 2rem;
   
  .nav-item {
    padding: 0.5rem 1rem;
    cursor: pointer;
    color: #666;
    transition: all 0.2s;
    border-bottom: 2px solid transparent;
    
    &.active {
      color: #ee5530;
      border-bottom-color: #ee5530;
    }
    
    &:hover {
      color: #ee5530;
    }
  }
}

/* 标签页内容 */
.tab-content {
  max-width: 75rem;
  margin: 0 auto 2rem;
}

/* 占位内容 */
.placeholder-content {
  background: white;
  border-radius: 0.5rem;
  padding: 4rem;
  text-align: center;
  color: #999;
  font-size: 1rem;
}
.status-item{
      margin-top: 1rem;
      color: #428b0f;
    }

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .product-detail-container {
    padding: 0 1rem;
  }
}
</style>
